package com.payment.web.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.constant.Constants;
import com.payment.common.utils.ImageUtil;
import com.payment.common.utils.StringUtils;
import com.payment.common.utils.aliyun.OSSClientUtil;
import com.payment.common.utils.file.FileUtils;
import com.payment.common.utils.pay.EncryptUtil;
import com.payment.system.config.GuangGuConfig;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.PypStore;
import com.payment.system.service.IAcqService;
import com.payment.system.service.IMerchantService;
import com.payment.system.service.IPypStoreService;
import com.payment.system.util.GuangGuUtil;
import com.payment.system.vo.OpenPypVo;
import com.payment.system.vo.PypAddStoreVo;
import com.payment.system.vo.PypReportVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author fuzhili
 * @Description: PYP
 * @date 2019/1/28 9:07
 */
@Controller
@RequestMapping("/app/pyp")
public class AppPypController {
    private static final Logger logger = LoggerFactory.getLogger(AppPypController.class);
    @Autowired
    private IAcqService acqService;
    @Autowired
    private IPypStoreService pypStoreService;
    @Autowired
    private IMerchantService merchantService;

    /**
     * 查询碰一碰签约情况
     *
     * @param merchantId
     * @return
     */
    @RequestMapping("/queryPypSgin")
    @ResponseBody
    public AjaxResult queryPypSgin(String merchantId) {
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error("用户信息不全");
        }
        PypStore store = pypStoreService.selectPypStoreByMerchantId(merchantId);
        if (store == null) {
            try {
                store = new PypStore();
                JSONObject json = GuangGuUtil.pypQuerySgin("3001", merchant.getAcqMerchantNo());
                if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                    store.setId(StringUtils.randomUUID());
                    store.setSginStatus(Integer.parseInt(json.getString("sgin_status")));
                    store.setMerchantId(merchantId);
                    pypStoreService.insertPypStore(store);
                    String bankCardNo = EncryptUtil.desDecrypt(json.getString("bank_card_no"), GuangGuConfig.keys);
                    bankCardNo = bankCardNo.substring(bankCardNo.length() - 4, bankCardNo.length());
                    return AjaxResult.successAndData("请求成功,请上传尾号为" + bankCardNo + "进行认证！", json.getString("sgin_status"));
                } else {
                    return AjaxResult.error(json == null ? "请求超时,请重试！" : json.getString("ret_msg"));
                }
            } catch (Exception e) {
                logger.error("查询碰一碰签约异常{}", e);
                return AjaxResult.error("请求超时,请重试！");
            }
        } else {
            return AjaxResult.successAndData("请求成功", store.getSginStatus());
        }
    }

    /**
     * 碰一碰商户进件
     *
     * @param merchantId
     * @return
     */
    @RequestMapping("/openPyp")
    @ResponseBody
    public AjaxResult openPyp(String merchantId, MultipartFile[] fileImg) {
        if (fileImg == null || fileImg.length < 1 || fileImg.length > 4 || StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "缺失必要参数！");
        }

        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error("用户信息不全");
        }
        String imgIdCardZ = "", imgIdCardF = "", imgBankZ = "", imgIdCardS = "";
        String yasuo = "";
        try {
            for (int i = 0; i < fileImg.length; i++) {
                if (!FileUtils.fileType(fileImg[i])) {
                    return AjaxResult.error(1, "图片类型错误");
                }
                if (fileImg[i].getSize() > (1024 * 800)) {
                    return AjaxResult.error(1, "上传图片大小不能超过800KB！");
                } else if (fileImg[i].getSize() > (1024 * 130)) {
                    yasuo = "?x-oss-process=image/quality,q_20";
                }


                if (i == 0) {
                    imgIdCardZ = OSSClientUtil.uploadImg2Oss(fileImg[i], Constants.MERCHANT_CARD + merchant.getPhone() + "/") + yasuo;
                } else if (i == 1) {
                    imgIdCardF = OSSClientUtil.uploadImg2Oss(fileImg[i], Constants.MERCHANT_CARD + merchant.getPhone() + "/") + yasuo;
                } else if (i == 2) {
                    imgIdCardS = OSSClientUtil.uploadImg2Oss(fileImg[i], Constants.MERCHANT_CARD + merchant.getPhone() + "/") + yasuo;
                } else if (i == 3) {
                    imgBankZ = OSSClientUtil.uploadImg2Oss(fileImg[i], Constants.MERCHANT_CARD + merchant.getPhone() + "/") + yasuo;
                } else {
                    return AjaxResult.error(1, "图片上传错误");
                }

            }
        } catch (Exception e) {
            logger.error("图片上传失败!请联系客服咨询", e);
            return AjaxResult.error("图片上传失败!请联系客服咨询");
        }


        PypStore store = pypStoreService.selectPypStoreByMerchantId(merchantId);
        if (store == null) {
            return AjaxResult.error("请先查询签约情况");
        }
        store.setIdCardZ(imgIdCardZ);
        store.setIdCardF(imgIdCardF);
        store.setIdCardS(imgIdCardS);
        store.setBankZ(imgBankZ);
        pypStoreService.updatePypStore(store);
        if (store.getSginStatus().equals(0)) {
            try {
                OpenPypVo openPypVo = new OpenPypVo();
                openPypVo.setSeriaNo(StringUtils.createNum());
                openPypVo.setCompanyId("3001");
                openPypVo.setUserId(merchant.getAcqMerchantNo());
                openPypVo.setBankCardNo(merchant.getBankAccount());
                openPypVo.setImgIdCardZ(ImageUtil.NetImageToBase64(imgIdCardZ));
                openPypVo.setImgIdCardF(ImageUtil.NetImageToBase64(imgIdCardF));
                openPypVo.setImgBankZ(ImageUtil.NetImageToBase64(imgBankZ));
                openPypVo.setImgIdCardS(ImageUtil.NetImageToBase64(imgIdCardS));
                openPypVo.setImgSuffix("jpg");

                JSONObject json = GuangGuUtil.openPyp(openPypVo);
                if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                    store.setSginStatus(1);
                    pypStoreService.updatePypStore(store);
                    return AjaxResult.successAndData("操作成功", store.getSginStatus());
                } else {
                    return AjaxResult.error(json == null ? "请求超时,请重试！" : json.getString("res_msg"));
                }
            } catch (Exception e) {
                logger.error("碰一碰商户进件异常{}", e);
                return AjaxResult.error("请求超时");
            }
        } else {
            return AjaxResult.successAndData("操作成功", store.getSginStatus());
        }

    }

    /**
     * 查询省市区/查询大小类别
     * type 1地区，2；类别
     *
     * @return
     */
    @RequestMapping("/queryResources")
    @ResponseBody
    public AjaxResult queryResources(String merchantId, String type, String value) {
        if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(type)) {
            logger.error("merchantId=={},type=={},value=={}", merchantId, type, value);
            return AjaxResult.error("缺失必要参数");
        }
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error("用户信息不全");
        }
        JSONObject json;
        try {
            if ("1".equals(type)) {
                if (StringUtils.isEmpty(value)) {
                    json = GuangGuUtil.pypQueryProvince("3001", merchant.getAcqMerchantNo());
                } else {
                    json = GuangGuUtil.pypQueryCity("3001", merchant.getAcqMerchantNo(), value);
                }
            } else if ("2".equals(type)) {
                if (StringUtils.isEmpty(value)) {
                    json = GuangGuUtil.pypQueryMcc("3001", merchant.getAcqMerchantNo());
                } else {
                    json = GuangGuUtil.pypQuerySubMcc("3001", merchant.getAcqMerchantNo(), value);
                }
            } else {
                return AjaxResult.error("暂无类型查询。");
            }

            if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                return AjaxResult.successAndData("获取信息成功", json.getJSONArray("data"));
            } else {
                return AjaxResult.error(json == null ? "请求超时,请重试！" : json.getString("ret_msg"));
            }

        } catch (Exception e) {
            logger.error("查询省市区/查询大小类别异常=={}", e);
            return AjaxResult.error("获取城市信息异常，请重试！");
        }
    }

    /**
     * 碰一碰商户报备获取验证码
     *
     * @param merchantId
     * @return
     */
    @RequestMapping("/sendSms")
    @ResponseBody
    public AjaxResult sendSms(String merchantId) {
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error("用户信息不全");
        }
        PypStore store = pypStoreService.selectPypStoreByMerchantId(merchantId);
        if (store == null) {
            return AjaxResult.error("请先查询签约情况");
        }
        if (store.getSginStatus().equals(1)) {
            try {
                JSONObject json = GuangGuUtil.pypSendSms("3001", merchant.getAcqMerchantNo(), merchant.getReservePhone());
                if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                    return AjaxResult.successAndData("请求成功", json.getString("smsid"));
                } else {
                    return AjaxResult.error(json == null ? "请求超时,请重试！" : json.getString("res_msg"));
                }
            } catch (Exception e) {
                logger.error("碰一碰商户报备获取验证码{}", e);
                return AjaxResult.error("请求超时");
            }
        }
        logger.error("碰一碰商户报备状态{}", store.getSginStatus());
        return AjaxResult.error("获取验证码失败");
    }


    /**
     * 碰一碰商户报备
     *
     * @return
     */
    @RequestMapping("/pypReport")
    @ResponseBody
    public AjaxResult pypReport(String merchantId, String smsCode, String smsId, String phone) {
        if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(smsCode) || StringUtils.isEmpty(smsId) || StringUtils.isEmpty(phone)) {
            logger.error("merchantId=={},smsCode=={},smsId=={},phone==={}", merchantId, smsCode, smsId, phone);
            return AjaxResult.error("缺失必要参数");
        }
        try {
            Merchant merchant = merchantService.selectMerchantById(merchantId);
            if (merchant == null) {
                return AjaxResult.error("用户信息不全");
            }
            PypReportVo pypReportVo = new PypReportVo();
            pypReportVo.setUserId(merchant.getAcqMerchantNo());
            pypReportVo.setCompanyId("3001");
            pypReportVo.setSmsCode(smsCode);
            pypReportVo.setSmsId(smsId);
            pypReportVo.setPhone(phone);
            JSONObject json = GuangGuUtil.pypReport(pypReportVo);
            PypStore store = pypStoreService.selectPypStoreByMerchantId(merchantId);
            if (store == null) {
                return AjaxResult.error("请先查询签约情况");
            }
            if (!store.getSginStatus().equals(1)) {
                return AjaxResult.error("该商户尚未上传证件信息照片");
            }
            if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                store.setSginStatus(2);
                pypStoreService.updatePypStore(store);
                return AjaxResult.success();
            } else {
                return AjaxResult.error(json == null ? "请求超时,请重试！" : json.getString("res_msg"));
            }
        } catch (Exception e) {
            logger.error("碰一碰商户报备{}", e);
            return AjaxResult.error("请求超时,请重试！");
        }
    }

    /**
     * 新增店铺
     *
     * @return
     */
    @RequestMapping("/addStore")
    @ResponseBody
    public AjaxResult addStore(PypReportVo pypReportVo, String merchantId) {
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error("用户信息不全");
        }
        PypStore store = savePypStore(pypReportVo, merchantId);
        if (store == null) {
            return AjaxResult.error("请先查询签约情况");
        }
        if (!store.getSginStatus().equals(2)) {
            return AjaxResult.error("该商户尚未报备");
        }
        //1.添加店铺
        try {
            pypReportVo.setNotfiyUrl("http");
            pypReportVo.setUserId(merchant.getAcqMerchantNo());
            pypReportVo.setCompanyId("3001");
            JSONObject json = GuangGuUtil.pypAddStore(getPypAddStoreVo(pypReportVo, merchant.getAcqMerchantNo()));
            if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                store.setSginStatus(3);
                pypStoreService.updatePypStore(store);
                return AjaxResult.success("新增店铺成功");
            } else {
                return AjaxResult.error(json == null ? "请求超时,请重试！" : json.getString("res_msg"));
            }
        } catch (Exception e) {
            logger.error("碰一碰添加商铺{}", e);
            return AjaxResult.error("请求超时,请重试！");
        }
    }

    /**
     * 纸卡 申请标签
     *
     * @return
     */
    @RequestMapping("/storeEffect")
    @ResponseBody
    public AjaxResult addStore(String merchantId, String uuid) {
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error("用户信息不全");
        }
        PypStore store = pypStoreService.selectPypStoreByMerchantId(merchantId);
        if (store == null) {
            return AjaxResult.error("请先查询签约情况");
        }
        if (!store.getSginStatus().equals(3)) {
            return AjaxResult.error("尚未添加店铺请先添加店铺");
        }
        try {
            JSONObject json = GuangGuUtil.pypStoreEffect("3001", merchant.getAcqMerchantNo(), uuid);
            if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                store.setUuid(uuid);
                String tag = json.getString("tag");
                store.setTag(tag);
                store.setSginStatus(4);
                pypStoreService.updatePypStore(store);
                return AjaxResult.successAndData("操作成功", tag);
            } else {
                return AjaxResult.error(json == null ? "请求超时,请重试！" : json.getString("res_msg"));
            }
        } catch (Exception e) {
            logger.error("纸卡 申请标签{}", e);
            return AjaxResult.error("请求超时,请重试！");
        }
    }


    /**
     * 纸卡 成功调用
     */
    @RequestMapping("/storeSuccess")
    @ResponseBody
    public AjaxResult storeSuccess(String merchantId) {
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error("用户信息不全");
        }
        PypStore store = pypStoreService.selectPypStoreByMerchantId(merchantId);
        if (store == null) {
            return AjaxResult.error("请先查询签约情况");
        }
        store.setSginStatus(4);
        pypStoreService.updatePypStore(store);
        return AjaxResult.success();

    }

    /**
     * 保存商铺信息
     */
    private PypStore savePypStore(PypReportVo pypReportVo, String merchantId) {
        PypStore store = pypStoreService.selectPypStoreByMerchantId(merchantId);
        store.setStoreName(pypReportVo.getStoreName());
        //store.setStoreCode();
        store.setMccCode(pypReportVo.getMccCode());
        store.setMccName(pypReportVo.getMccName());
        store.setSubMccCode(pypReportVo.getSubMccCode());
        store.setStoreName(pypReportVo.getStoreName());
        store.setProvinceCode(pypReportVo.getProvinceCode());
        store.setProvinceName(pypReportVo.getProvinceName());
        store.setCityCode(pypReportVo.getCityCode());
        store.setCityName(pypReportVo.getCityName());
        store.setCountyCode(pypReportVo.getCountyCode());
        store.setCountyName(pypReportVo.getCountyName());
        pypStoreService.updatePypStore(store);
        return store;
    }

    /**
     * 封装获取添加商铺信息
     *
     * @param pypReportVo
     * @return
     */
    private PypAddStoreVo getPypAddStoreVo(PypReportVo pypReportVo, String userId) {
        PypAddStoreVo addStoreVo = new PypAddStoreVo();
        //todo 回调地址待定
        addStoreVo.setNotfiyUrl(GuangGuConfig.PYP_PAYMENT_URL);
        addStoreVo.setCompanyId("3001");
        addStoreVo.setUserId(userId);
        addStoreVo.setStoreName(pypReportVo.getStoreName());
        addStoreVo.setMccCode(pypReportVo.getMccCode());
        addStoreVo.setMccName(pypReportVo.getMccName());
        addStoreVo.setSubMccCode(pypReportVo.getSubMccCode());
        addStoreVo.setSubMccName(pypReportVo.getSubMccName());
        addStoreVo.setProvinceCode(pypReportVo.getProvinceCode());
        addStoreVo.setProvinceMame(pypReportVo.getProvinceName());
        addStoreVo.setCityCode(pypReportVo.getCityCode());
        addStoreVo.setCityName(pypReportVo.getCityName());
        addStoreVo.setCountyCode(pypReportVo.getCountyCode());
        addStoreVo.setCountyName(pypReportVo.getCountyName());
        return addStoreVo;
    }


}
